/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-02 14:32:10
 * @LastEditTime: 2024-02-04 17:59:51
 */
import useUserStore from '@g/store/modules/user'
import { ikStore, ikTree } from 'iking-utils'
import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import { systemConfig } from '../../system.config'
import { postApi } from '@/MainApp/apis/post'
import { depApi } from '@/MainApp/apis/dep'
import { roleApi } from '@/MainApp/apis/role'
import { commonApi } from '@/MainApp/apis/common'
import type { ISearchForm } from '@/global/enums/search'
// 自动生成TS返回参数类型
import '@intlify/core-base'

export enum ETableIconType {
  图标 = 'icon',
  文字 = 'title',
  文字图标 = 'all'
}

// 通用配置及规范配置
export const useConfig = () => {
  const userStore = useUserStore()
  // 国际化
  const { t, te, locale } = useI18n()

  // dialog大小
  const dialog = {
    // 大
    xl: 1024,
    // 中
    l: 683,
    // 小
    sl: 512
  }

  // drawer 大小
  const drawer = {
    // 全屏
    full: '100%',
    // 大
    xl: '1024px',
    // 中
    l: '683px',
    // 小
    sl: '512px'
  }

  // 表格操作列宽度 - 按照按钮个数
  const operateCol = {
    three: '148px',
    two: '106px',
    one: '64px'
  }

  // 仅在setup内适用
  // 当前路由信息
  const { path } = useRoute()
  // 当前登录用户信息
  const user = userStore.userInfo

  return {
    t,
    te,
    locale,
    dialog,
    drawer,
    path,
    user,
    operateCol
  }
}

// 字段长度
export const useLength = () => {
  return {
    // 短名称
    lenShort: 8,
    // 手机号
    lenPhone: 11,
    // 名称、标题
    lenName: 45,
    // 描述、内容
    lenContent: 200,
    // 链接
    lenLink: 128,
    // 长文本
    lenLargeContent: 2000
  }
}

// token
export const useToken = () => {
  return ikStore.local.getItem(import.meta.env.VITE_GLOB_APP_TOKEN_NAME)
}

// menu-id
export const useMenuId = async () => {
  return await ikStore.forage.getItem('menuid')
}

// 抛出系统内各地址
export const useHttpUrl = () => {
  const { VITE_APP_API_BASEURL, VITE_APP_UPLOAD_URL, VITE_APP_DOWNLOAD_URL, VITE_APP_SOCKET_URL, VITE_APP_PREVIEW_URL, VITE_APP_APPLICATION_PAGE_MOBILE_URL }
    = import.meta.env

  const setFileUrl = (url: string) => {
    return url
      ? url.startsWith('http')
        ? url
        : `${VITE_APP_DOWNLOAD_URL}${url}`
      : ''
  }

  return {
    baseUrl: VITE_APP_API_BASEURL,
    uploadUrl: VITE_APP_UPLOAD_URL,
    loadUrl: VITE_APP_DOWNLOAD_URL,
    socketUrl: VITE_APP_SOCKET_URL,
    previewUrl: VITE_APP_PREVIEW_URL,
    applicationPageMobileUrl: VITE_APP_APPLICATION_PAGE_MOBILE_URL,
    // 拼接URL
    setFileUrl
  }
}

// 部门数据
export const useDep = async (): Promise<{ [key: string]: any; }> => {
  const { success, data } = await depApi.getAllDeps()
  if (success) {
    const fixData = data?.map((li: { name: any; id: any;[key: string]: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    return fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
  }
  return []
}

// 岗位数据
export const usePost = async (): Promise<{ [key: string]: any; }> => {
  const { success, data } = await postApi.getAllPosts()
  if (success) {
    const fixData = data?.map((li: { name: any; id: any;[key: string]: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    return fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
  }
  return []
}

// 角色数据
export const useRole = async (): Promise<{ [key: string]: any; }> => {
  const { success, data } = await roleApi.getRoleList()
  if (success) {
    const fixData = data?.map((li: { name: any; id: any;[key: string]: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    return fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
  }
  return []
}

// 表格通用字段 默认不显示
export const useTableKey = (): ISearchForm[] => {
  return [
    {
      key: 'createTime',
      value: '',
      label: '创建时间',
      width: 170,
      valueFormat: 'YYYY-MM-DD',
      type: EFormType.date,
      search: false
    },
    {
      key: 'updateTime',
      value: '',
      label: '更新时间',
      valueFormat: 'YYYY-MM-DD',
      width: 170,
      type: EFormType.date,
      search: false
    }
  ]
}

// 表格列 排序
export const useSortMethod = () => {
  const tableKeys: Ref<any[]> = ref([])
  const handSortList = (sorts: ISearchForm[]) => {
    tableKeys.value = sorts
  }
  return {
    tableKeys,
    handSortList
  }
}

export const usePickerData = () => {
  const userList = ref([])
  const depList = ref([])
  const roleList = ref([])
  const postList = ref([])

  const handData = async (val?: any) => {
    const isStr = typeof val === 'string'
    const param = {
      parentDepartmentId: isStr ? val : val?.id,
      name: isStr ? '' : val?.name
    }
    const { success, data } = await commonApi.getAllComData(param)
    if (!success)
      return
    const { departments, roles, posts, users } = data
    depList.value = departments
    userList.value = users
    roleList.value = roles
    postList.value = posts
    return {
      departments,
      users,
      roles,
      posts
    }
  }
  handData()

  const handSetChild = (item: any) => {
    handData(item?.elementId)
  }

  return {
    userList,
    depList,
    roleList,
    postList,
    handData,
    handSetChild
  }
}

// 设置tag颜色
export const useTagColor = () => {
  const map = new Map()
  let i = 1
  const setColor = (list: any[]) => {
    return list.map((li: any) => {
      const title = li?.title || li
      if (!map.has(title)) {
        map.set(title, `var(--ik-statu-color-${i})`)
        map.set(`${title}-bg`, `var(--ik-statu-color-${i}-light)`)
        i++
        if (i > 8)
          i = 1
      }
      return {
        title,
        type: '',
        color: map.get(title),
        background: map.get(`${title}-bg`)
      }
    })
  }

  return {
    setColor
  }
}

// 统一前缀
export const usePrefix = () => {
  return 'ik'
}

// 表格按钮显示样式
export const useTableIconType = () => {
  return systemConfig.table?.btnType || ETableIconType.图标
}

export const SYSTEM_ICON_TYPE = systemConfig.table?.btnType

const _ICON_TYPE = systemConfig.table?.btnType === ETableIconType.图标

export const useOperateWidth = (min: number, max: number) => {
  return _ICON_TYPE ? min : max
}
